'use client';

import { useEffect, useState } from 'react';
import { useWeb3Modal } from '@web3modal/wagmi/react';
import { useAccount, useDisconnect, useSwitchChain } from 'wagmi';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';

interface EnhancedWalletButtonProps {
  chain: 'bsc' | 'xlayer' | 'solana';
  className?: string;
}

export function EnhancedWalletButton({ chain, className = '' }: EnhancedWalletButtonProps) {
  const [mounted, setMounted] = useState(false);
  
  // Web3Modal hooks (for EVM chains including X Layer with OKX Wallet)
  const { open } = useWeb3Modal();
  const { address: wagmiAddress, isConnected: wagmiConnected, chain: currentChain } = useAccount();
  const { disconnect: wagmiDisconnect } = useDisconnect();
  const { switchChain } = useSwitchChain();
  
  // Legacy wallet context (for Solana)
  const { connected: legacyConnected, address: legacyAddress, disconnectWallet: legacyDisconnect } = useMultiChainWallet();

  useEffect(() => {
    setMounted(true);
  }, []);

  // Determine which system to use based on chain
  const useLegacyForChain = chain === 'solana';
  const useWagmiForChain = chain === 'bsc' || chain === 'xlayer';

  // Get active connection status and address
  const isConnected = useWagmiForChain ? wagmiConnected : legacyConnected;
  const address = useWagmiForChain ? wagmiAddress : legacyAddress;

  // Chain ID mapping
  const chainIdMap: Record<'bsc' | 'xlayer', number> = {
    bsc: 56,
    xlayer: 196,
  };

  const handleConnect = async () => {
    if (useWagmiForChain) {
      // Use Web3Modal for EVM chains (BSC, X Layer)
      // This will show OKX Wallet, MetaMask, WalletConnect, etc.
      open();
    } else {
      // For Solana, fall back to legacy system
      // You might want to implement Phantom wallet connection here
      alert('Please select BSC or X Layer for Web3Modal wallet connection. Solana support coming soon!');
    }
  };

  const handleDisconnect = async () => {
    if (useWagmiForChain) {
      wagmiDisconnect();
    } else {
      await legacyDisconnect();
    }
  };

  // Auto-switch to correct chain if connected but on wrong chain
  useEffect(() => {
    if (mounted && wagmiConnected && useWagmiForChain && currentChain) {
      const targetChainId = chainIdMap[chain];
      if (currentChain.id !== targetChainId) {
        console.log(`Auto-switching from chain ${currentChain.id} to ${targetChainId}`);
        switchChain({ chainId: targetChainId });
      }
    }
  }, [mounted, wagmiConnected, useWagmiForChain, currentChain, chain, switchChain]);

  if (!mounted) {
    return (
      <button
        className={`wallet-adapter-button wallet-adapter-button-trigger ${className}`}
        disabled
      >
        Loading...
      </button>
    );
  }

  if (isConnected && address) {
    return (
      <div className="flex items-center gap-2">
        {/* Show chain mismatch warning for wagmi */}
        {useWagmiForChain && currentChain && currentChain.id !== chainIdMap[chain] && (
          <button
            onClick={() => switchChain({ chainId: chainIdMap[chain] })}
            className="px-2 py-1 text-xs bg-orange-500/20 hover:bg-orange-500/30 border border-orange-500/50 rounded text-orange-400"
          >
            Switch to {chain === 'xlayer' ? 'X Layer' : 'BSC'}
          </button>
        )}
        
        <button
          onClick={handleDisconnect}
          className={`wallet-adapter-button wallet-adapter-button-trigger ${className}`}
          type="button"
        >
          {address.slice(0, 4)}...{address.slice(-4)}
          {useWagmiForChain && currentChain && ` (${currentChain.name})`}
        </button>
      </div>
    );
  }

  return (
    <button
      onClick={handleConnect}
      className={`wallet-adapter-button wallet-adapter-button-trigger ${className}`}
      type="button"
    >
      Connect Wallet
    </button>
  );
}
